package cn.itcast.service.system.impl;

import cn.itcast.dao.system.ModuleDao;
import cn.itcast.dao.system.RoleDao;
import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.Role;
import cn.itcast.service.system.RoleService;
import cn.itcast.service.utils.RedisUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private ModuleDao moduleDao;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public PageInfo<Role> findByPage(Integer pageNum, Integer pageSize,String companyId) {
        PageHelper.startPage(pageNum,pageSize);
        List<Role> list = roleDao.findAll(companyId);
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    //查询企业的所有角色
    @Override
    public List<Role> findAll(String companyId) {
        List<Role> list = roleDao.findAll(companyId);
        return list;
    }

    @Override
    public void save(Role role) {
        role.setId(UUID.randomUUID().toString());
        roleDao.save(role);
    }

    @Override
    public void update(Role role) {
        roleDao.update(role);
    }

    @Override
    public Role findById(String id) {
        Role role = roleDao.findById(id);
        return role;
    }

    @Override
    public Boolean delete(String id) {
        roleDao.delete(id);
        return null;
    }

    //3、根据用户id查找该用户已分配的角色
    @Override
    public List<Role> findUserRoleByUserId(String id) {
        return roleDao.findUserRoleByUserId(id);
    }

    //更新角色的权限
    @Override
    public void updateRoleModule(String roleid, String[] moduleIds) {
        roleDao.deleteRoleModuleByRoleId(roleid);
        roleDao.addRoleModule(roleid,moduleIds);
        //更新redis中的缓存
        try {
            List<Module> roleModuleList = moduleDao.findRoleModuleByRoleId(roleid);
            String key = "roleModuleList_" + roleid;
            String value = new ObjectMapper().writeValueAsString(roleModuleList);
            redisUtil.set(key,value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
